package com.hh.releasenode.utils;

import com.hh.releasenode.exception.RNException;
import org.apache.commons.lang.StringUtils;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * @ClassName GenerateRandomUtils
 * @Description 生成随机数
 * @Author KunxianLi
 * Date 2020/6/30 15:31
 * Version 1.0
 **/
public class RandomStrUtils {

    private static final char[] hexCode = "0123456789abcdef".toCharArray();

    /**
     * @Author KunxianLi
     * @Description TODO 
     * @Date 2020/6/30 15:34
     * @Param [prefix, suffix]
     * @return java.lang.String
     **/
    public static String generateToken(String prefix,String suffix){

        String value = generateValue(UUID.randomUUID().toString());

        if(StringUtils.isNotBlank(prefix)){
            value = prefix+"_"+value;
        }

        if(StringUtils.isNotBlank(prefix)){
            value = "_"+value+"_"+suffix;
        }

        return value;
    }

    public static String toHexString(byte[] data) {
        if(data == null) {
            return null;
        }
        StringBuilder r = new StringBuilder(data.length*2);
        for ( byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

    public static String generateValue(String param) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(param.getBytes());
            byte[] messageDigest = algorithm.digest();
            return toHexString(messageDigest);
        } catch (Exception e) {
            throw new RNException("生成Token失败");
        }
    }


}
